import React, { useRef, useState } from 'react';
import { Row, Col, Popconfirm, Button, Space } from 'antd';
import ProForm, {
  DrawerForm,
  ProFormSwitch,
  ProFormTextArea,
  ProFormInstance,
  ProFormSelect,
} from '@ant-design/pro-form';
import type { ActionType, EditableFormInstance, ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import * as c from '@/services/consts';
import * as api from '@/services/vpnServerDeploy';
import Form from './BatchForm';

type VpnServerFormProps = {
  visible: boolean;
  current: API.VpnServerDeploy | undefined;
  onCancel: () => void;
  onSubmit: (values: API.VpnServerDeployForm) => Promise<void>;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } = props;

  if (!visible) {
    return null;
  }
  const formRef = useRef<ProFormInstance>();
  const editorFormRef = useRef<EditableFormInstance<API.VpnServerDeployServer>>();
  const editorActionRef = useRef<ActionType>();

  const [dataSource, setDataSource] = useState<API.VpnServerDeployForm|undefined>(undefined);
  const [serverSource, setServerSource] = useState<API.VpnServerDeployServer[]|undefined>(undefined);
  const [formBatchVpnServerVisible, setFormBatchVpnServerVisible] = useState<boolean>(false);

  const [selectIds, setSelectIds] = useState<any[]>([]);
  // const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();
  

  const loadData = async () => {
    if(current){
      const result = await api.getform({id:current.id});
      if (result && result.success) {
        setDataSource(result.data);
        setServerSource(result.data.servers);
      }
      return Promise.resolve(result.data);
    }
    else{
      let empty : API.VpnServerDeployForm = {id:'', status:0, udp:true, serverType: undefined};
      return Promise.resolve(empty);
    }
  };
  


  
  const handleIdsSubmit = async (ids: string) => {
    if (ids == undefined || ids == '') return;
    ids = ids.replaceAll('\r', '');
    let iplist = ids.split('\n');

    // let rows = editorFormRef.current?.getRowsData?.() ?? [];
    let rows: API.VpnServerDeployServer[] = [];
    if(serverSource){
      for (let item of serverSource) {
        rows.push(item);
      }
    }

    for (let id of iplist) {
      if(id != ''){
        let numId = parseInt(id);
        if(numId){
          let ex = rows.find((val) => {return val.id == numId});
          // console.log(ex);
          if(ex) continue;
          let record: API.VpnServerDeployServer = {
            id: numId,
            ip: '',
          };
          rows.push(record);
        }
      }
    }

    // console.log(rows);
    setServerSource(rows);
    setFormBatchVpnServerVisible(false);
  };

  
  const handleBatchRemoveIps = async (onCleanSelected:any) => {
    if (serverSource.length == 0) return;

    let rows: API.VpnServerDeployServer[] = [];
    for (let item of serverSource) {
      if(selectIds.includes(item.id)) continue;
      rows.push({
        id: item.id,
        ip: item.ip,
      });
    }
    // console.log(rows);
    setServerSource(rows);
    setSelectIds([]);
    onCleanSelected();
  };
  

  const netConfigColumns: ProColumns<API.VpnServerDeployServer>[] = [
    {
      title: '服务器实例ID',
      dataIndex: 'id',
    },
    {
      title: '服务器IP',
      dataIndex: 'ip',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
      render: (text, record, _, action) => [
        <Popconfirm
          key="delete"
          title="确定要删除吗?"
          onConfirm={async () => {
            const tableDataSource = formRef.current?.getFieldValue(
              'servers',
            ) as API.VpnServerDeployServer[];
            formRef.current?.setFieldsValue({
              servers: tableDataSource?.filter(
                (item) => item.id !== record.id,
              ),
            });
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleFormSubmit = async (record: API.VpnServerDeployForm) => {
    console.log(record);
    onSubmit(record);
  };

  return (
    <DrawerForm<API.VpnServerDeployForm>
      visible={visible}
      // initialValues={dataSource}
      title={`${dataSource ? '编辑' : '添加'}服务器部署`}
      formRef={formRef}
      autoFocusFirstInput
      width={1000}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      request={loadData}
    >
      <Row gutter={24}>
        <Col span={6}>
          <ProFormSelect
            name="serverType"
            label="服务器类型"
            placeholder="请选择服务器类型"
            rules={[{ required: true, message: '请选择服务器类型' }]}
            options={c.ServerDeployServerTypeOptions}
          />
        </Col>
        <Col span={6}>
          <ProFormSelect
            name="type"
            label="部署类型"
            placeholder="请选择部署类型"
            rules={[{ required: true, message: '请选择部署类型' }]}
            options={c.ServerDeployTypes}
          />
        </Col>
        <Col span={4}>
          <ProFormSwitch
            name="udp"
            label="启用UDP"
            fieldProps={{
              defaultChecked: true,
            }}
          />
        </Col>
        {/* <Col span={4}>
          <ProFormSwitch
            name="waiting"
            label="等待"
            fieldProps={{
              defaultChecked: false,
            }}
          />
        </Col> */}

        <Col span={24}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
        <Col span={24}>
          <ProForm.Item
            name="servers"
            label={
              <>
                部署服务器列表　
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    setFormBatchVpnServerVisible(true);
                  }}
                >
                  批量添加服务器
                </Button>
              </>
            }
          >
            <EditableProTable<API.VpnServerDeployServer>
              rowKey="id"
              editableFormRef={editorFormRef}
              actionRef={editorActionRef}
              locale={{ emptyText: '暂无数据' }}
              toolBarRender={false}
              columns={netConfigColumns}
              defaultValue={serverSource}
              // onChange={setDataSource}
              recordCreatorProps={false}
              // editable={{
              //   // type: 'multiple',
              //   //type: 'single',
              //   editableKeys,
              //   actionRender: (row, config, defaultDom) => [
              //     //defaultDom.save,
              //     defaultDom.delete,
              //   ],
              //   onValuesChange: (record, recordList) => {
              //     setServerSource(recordList);
              //   },
              //   onChange: setEditableRowKeys,
              // }}
              request={async () => ({
                data: serverSource,
                success: true,
              })}
              params={{ 
                d: serverSource
               }}
              rowSelection={{
                defaultSelectedRowKeys: [],
                onChange:(selectedRowKeys)=>{
                  setSelectIds(selectedRowKeys);
                }
              }}
              tableAlertRender={({
                selectedRowKeys,
                // selectedRows,
                onCleanSelected,
              }) => (
                <Space size={24}>
                  {/* {setSelectIds(selectedRowKeys)} */}
                  <span>
                    已选 {selectedRowKeys.length} 条记录
                    <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                      取消选择
                    </a>
                  </span>
      
                  <span>
                      <Popconfirm
                        key="removeIps"
                        title="确定要批量删除？"
                        onConfirm={async () => {
                          console.log(selectIds);
                          handleBatchRemoveIps(onCleanSelected);
                        }}
                      >
                        <a>删除</a>
                      </Popconfirm>
                  </span>
                </Space>
              )}
            />
          </ProForm.Item>
        </Col>
      </Row>
      <Form
        visible={formBatchVpnServerVisible}
        onCancel={() => {
          setFormBatchVpnServerVisible(false);
        }}
        onSubmit={handleIdsSubmit}
      />

    </DrawerForm>
  );
};

export default VpnServerForm;
